import os
import time
import hashlib
from functools import wraps
import gradio as gr
from PIL import Image
import torch
from torch import nn
import numpy as np
from modelscope import AutoModel, AutoTokenizer, AutoImageProcessor
from diskcache import Cache
from ahocorasick import Automaton
import onnxruntime as ort




# ==================== 配置部分 ====================
class AppConfig:
    MODEL_PATHS = {
        'GLM-Edge-2B': 'path/to/glm-edge-2b',
        'Qwen-VL': 'path/to/qwen-vl'
    }
    SAFE_WORDS = ["暴力", "色情", "诈骗", "毒品"]  # 敏感词列表
    CACHE_DIR = "./cache"
    ONNX_PROVIDERS = ['CUDAExecutionProvider', 'CPUExecutionProvider']

# ==================== 工具模块 ====================
def timing_decorator(func):
    """性能监控装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs) 
        end = time.time()
        print(f"{func.__name__} 执行时间: {end - start:.2f}s")
        return result
    return wrapper


class SafetyFilter:
    """安全过滤模块"""
    def __init__(self):
        self.automaton = Automaton()
        for idx, word in enumerate(AppConfig.SAFE_WORDS):
            self.automaton.add_word(word, (idx, word))
        self.automaton.make_automaton()
    
    def filter_text(self, text):
        found = set()
        for end_index, (original_id, original_value) in self.automaton.iter(text):
            found.add(original_value)
        return text if not found else "[内容已过滤]"
